// 导入getToken,setToken,removeToken
import { getToken, setToken, removeToken } from '@/utils/auth'
// 导入login
import { login } from '@/api/user'
// 导入getUserInfo
import { getUserInfo } from '@/api/user'
// 引入constantRouters
import { constantRoutes, resetRouter } from '@/router'

const state = {
  token: getToken(),
  userInfo: {}, // 用户信息
  routes: constantRoutes // 默认路由
}

const mutations = {
  setToken(state, token) {
    state.token = token
    //
    setToken(token)
  },
  // 退出token
  removeToken(state) {
    state.token = null
    removeToken()
    // 重置路由
    resetRouter()
  },
  setUserInfo(state, data) {
    state.userInfo = data
  },
  // 设置路由
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes]
  }
}

const actions = {
  async  login(context, data) {
    console.log(data)
    const token = await login(data)
    console.log(token)
    context.commit('setToken', token)
  },
  // 获取用户信息
  async getUserInfo(context) {
    const res = await getUserInfo()
    context.commit('setUserInfo', res)
    return res // 返回数据
  },
  // 退出登录的action
  logout(context) {
    context.commit('removeToken') // 删除token
    context.commit('setUserInfo', {}) // 设置用户信息为空对象
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
